package org.wx.io.bio;

import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * BIO测试
 *
 * @author wangxun
 * @version 1.0
 * @description: 创建一个阻塞的服务端
 * @date 2021/1/28 10:52 上午
 */
public class BioTest {
    final Logger logger = LoggerFactory.getLogger(getClass());

    @Test
    void serverTest() {
        /**
         * 1. 建立线程池
         * 2. 建立serverSocket
         * 3. 开启监听
         * 4. 线程池开启处理
         */
        ExecutorService pool = Executors.newCachedThreadPool();
        ServerSocket serverSocket;
        try {
            logger.info("开启监听...");
            serverSocket = new ServerSocket(8999);
            while (true) {
                Socket socket = serverSocket.accept();
                pool.execute(() -> {
                    try {
                        socketHandler(socket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 处理读写的socket
     *
     * @param socket 读写的socket
     */
    private void socketHandler(Socket socket) throws IOException {
        InputStream inputStream = socket.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(inputStream);
        byte[] bytes = new byte[1024];
        int length;
        while ((length = bis.read(bytes)) != -1) {
            System.out.println(new String(bytes, 0, length));
            System.out.println("==============");
        }
    }
}
